//如果本地没有令牌，直接跳到登录页
//console.log(window.location.href);
if (window.location.href == 'http://localhost/login.html' || window.location.href == 'http://localhost') {

} else {
  if (!localStorage.getItem('WD-TOKEN')) {
    location.href = "/login.html";
  }
}


const ajax = axios.create({
  baseURL:'http://localhost:9999',//没有用nginx代理服务端服务器路径时
  //baseURL: '/api',//nginx代理服务端服务器路径时
  timeout: 30000
});


let wd__load__idx = null;//加载提示索引号

//请求拦截器
ajax.interceptors.request.use((config) => {
  // Do something before request is sent
  if(wd__load__idx){
    layer.close(wd__load__idx);//关闭加载提示
  }
  wd__load__idx = layer.load();//显示加载提示
  const token = localStorage.getItem('WD-TOKEN');
  config.headers['Token'] = token;//设置请求头 Token=token值
  return config;
}, function (error) {
  // Do something with request error
  if(wd__load__idx){
    layer.close(wd__load__idx);//关闭加载提示
  }
  return Promise.reject(error);
});


//对请求进行封装的函数，其中promise是get、post等请求的返回对象，okAction是操作成功后执行函数
const req = (promise, okAction) => {

  promise.then(response => {//正常响应
    if(wd__load__idx){
      layer.close(wd__load__idx);//关闭加载提示
    }
    const result = response.data;

    if (result.success) {

      okAction(result);

    } else {

      layer.msg(result.message, { icon: 2,time: 1500 }, () => {

        if (result.code == 520) {

          location.href = "/login.html"
        }
      });
    }

  }).catch(error => {
    if(wd__load__idx){
      layer.close(wd__load__idx);//关闭加载提示
    }
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      //console.log(error.response.data);
      //console.log(error.response.status);
      //console.log(error.response.headers);
      layer.msg("服务器错误！代码："+error.response.status, { icon: 2,time: 1500 });

    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      //console.log(error.request);
      layer.msg("服务器无响应！", { icon: 2,time: 1500 });
    } else {
      // Something happened in setting up the request that triggered an Error
      //console.log('请求错误！', error.message);
      console.log(error);
      layer.msg("请求错误！", { icon: 2,time: 1500 });
    }
    
  });

};


